package Flink.transformation;

import Flink.bean.WaterSensor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class KeyByAggr {
    public static void main(String[] args) throws Exception {
        /*
        * 对于Flink而言，DataStream是没有直接进行聚合的API的。因为我们对海量数据做聚合
肯定要进行分区并行处理，这样才能提高效率。所以在Flink中，要做聚合，需要先进行分区；
这个操作就是通过keyBy来完成的。
        * */

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<WaterSensor> stream = env.fromElements(
                new WaterSensor("sensor_1", 1L, 1),
                new WaterSensor("sensor_1", 2L, 2),
                new WaterSensor("sensor_2", 2L, 2),
                new WaterSensor("sensor_3", 3L, 3)
        );
        //  方式一：使用匿名类实现KeySelector
        stream.keyBy(new KeySelector<WaterSensor, String>() {
            @Override
            public String getKey(WaterSensor value) throws Exception {
                return value.getId();
            }
        }).print();
        // 方式二：使用Lambda表达式
//        stream.keyBy(data -> data.getId()).print();

        env.execute();
    }
}
